package cloud.simple.service;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import cloud.simple.model.User;
import cloud.simple.util.AppUtil;

@Service
public class UserService {
	@Autowired
    AppUtil appUtil;
	
	@Autowired
	RestTemplate restTemplate;
	
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	final String SERVICE_NAME="cloud-simple-service";
	
	@HystrixCommand(fallbackMethod="fallbackSearchAll")
	public List<User> searchAll(){
		//启用cloud.simple.config.ConfigClass时的方法
//		ServiceInstance instance = loadBalancerClient.choose(SERVICE_NAME);
//		URI uri = instance.getUri();
//        String url = uri.toString() + "/user";

		//使用WebApplication里的restTemplate注入时
		String url = "http://"+SERVICE_NAME+"/user";
		return restTemplate.getForObject(url, List.class);
	}
	
	private List<User> fallbackSearchAll(){
		System.out.println("HystrixCommand fallbackMethod handle!");
		  List<User> ls = new ArrayList<User>();

          User user = new User();

          user.setUsername("TestHystrix");

          ls.add(user);

          return ls;
	}
}
